package pers.qianyu.month_202012.date_20201207;

import org.junit.*;

/**
 * 978. 最长湍流子数组
 * https://leetcode-cn.com/problems/longest-turbulent-subarray/
 *
 * @author mizzle rain
 * @date 2020-12-07 14:47
 */
public class MaxTurbulenceSize {
    /**
     * 动态规划解法
     */
    public int maxTurbulenceSize(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        //表示以 arr[i] 结尾的湍流子数组
        int[] dp = new int[arr.length];
        dp[0] = 1;
        for (int i = 1; i < dp.length; i++) {
            int cur = arr[i];
            int pre = arr[i - 1];
            if (i == 1) {
                if (cur != pre) {
                    dp[i] = 2;
                }
                continue;
            }
            int prePre = arr[i - 2];
            if ((prePre < pre && pre > cur) ||
                    (prePre > pre && pre < cur)) {
                dp[i] = dp[i - 1] + 1;
            } else if (cur != pre) {
                dp[i] = 2;
            }
        }
        //System.out.println(Arrays.toString(dp));
        int res = dp[0];
        for (int i = 1; i < dp.length; i++) {
            if (dp[i] > res) {
                res = dp[i];
            }
        }
        return res;
    }

    @Test
    public void test1() {
        int[] arr = {9, 4, 2, 10, 7, 8, 8, 1, 9};
        int result = new MaxTurbulenceSize().maxTurbulenceSize(arr);
        System.out.println("result = " + result);
    }
}
